<?php
class Mozg_Storage
{
	static protected function GetFile($fileName)
	{
		return $fileName. '.json';
	}

	static public function Exists($fileName)
	{
		return is_file(self::GetFile($fileName));
	}

	static public function Readable($fileName)
	{
		return is_readable(self::GetFile($fileName));
	}

	static public function Writable($fileName)
	{
		return is_writable(self::GetFile($fileName));
	}

	static public function ModificationTime($fileName)
	{
		if (!self::Exists($fileName)) return false;
		return filemtime(self::GetFile($fileName));
	}

    static public function Read($fileName)
    {
		if (!self::Exists($fileName))
		{
			throw new Mozg_Exception_System('Storage file ' .$fileName. ' not found');
		}

    	if (!self::Readable($fileName))
		{
			throw new Mozg_Exception_System('Storage file ' .$fileName. ' not readable');
		}

		$data = Mozg::Lib('Json')->Decode(file_get_contents(self::GetFile($fileName)), true);
		if (null === $data)
		{
			throw new Mozg_Exception_System('Invalid data format in file ' .$fileName);
		}

		return $data;
    }

    static public function Save($fileName, $data)
    {
    	if (self::Exists($fileName) && !self::Writable($fileName))
		{
			throw new Mozg_Exception_System('Storage file ' .$fileName. ' not writable');
		}

		$file = self::GetFile($fileName);

		$path = pathinfo($file);
		if (!Mozg::Lib('dir')->Create($path['dirname'])) throw new Mozg_Exception_System(Mozg_Lang::_('UNABLE_CREATE_CONFIG_DIRECTORY'));

		file_put_contents($file, Mozg::Lib('Json')->Encode($data, JSON_FORCE_UTF));
		@chmod($file, _CHMOD_FILE);

    	return true;
    }

    static public function Delete($fileName)
    {
    	if (!self::Exists($fileName)) return true;

    	if (!self::Writable($fileName))
		{
			throw new Mozg_Exception_System('Storage file ' .$fileName. ' not writable');
		}

		$file = self::GetFile($fileName);
		unlink($file);

    	return true;
    }
}